package com.youyun56.gps.android.service;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

import com.youyun56.gps.android.common.CommandFactory;
import com.youyun56.gps.android.common.Location;
import com.youyun56.gps.android.common.LocationHelper;
import com.youyun56.gps.android.common.NetWorkUtil;
import com.youyun56.gps.android.common.RadioType;
import com.youyun56.gps.android.http.HttpManager;

public class UploadLocationService extends BroadcastReceiver {
    private final static String tag        = UploadLocationService.class.getName();
    public Location             location;
    private LocationManager     locationManager;
    private long                lastUpload = -1;
    private long                now        = -1;
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (LocationUploadService.getInstance() != null && LocationUploadService.getInstance().getCar() != null) {
            Boolean openBefore = NetWorkUtil.isGprsOpen(context);
            Boolean screenOn = LocationUploadService.getInstance().acquireWakeLock();
            try {
                Log.i(tag, "upload Position");
                if (!openBefore) {
                    NetWorkUtil.openGprs(context, true);
                }
                Thread thread = new Thread(new CdmaLocationClaimer(context));
                thread.start();
                thread.join();
                if (location != null) {
                    HttpManager.getInstance().excutePost(CommandFactory.uploadLocation(location, intent.getLongExtra("id", 0)));
                } else {
                    // LocationUploadService.getInstance().write("can not get location",
                    // true);
                }
                location = null;
            } catch (Exception e) {
                Log.e(tag, e.getMessage(), e);
            } finally {
                if (!openBefore || !screenOn) {
                    NetWorkUtil.openGprs(context, false);
                }
                LocationUploadService.getInstance().releaseWakeLock();
            }
        }
    }
    
    class CdmaLocationClaimer implements Runnable {
        private Context context;
        
        public CdmaLocationClaimer(Context context) {
            // TODO Auto-generated constructor stub
            this.context = context;
        }
        
        @Override
        public void run() {
            Log.i(tag, "run cdmaLocation");
            try {
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                String netOperator = telephonyManager.getNetworkOperator();
                String mobileCountryCode = "";
                String mnc = "";
                if (netOperator != null && netOperator.length() >= 5) {
                    mobileCountryCode = netOperator.substring(0, 3);
                    mnc = netOperator.substring(3, 5);
                }
                if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
                    GsmCellLocation gsm = (GsmCellLocation) telephonyManager.getCellLocation();
                    if (gsm != null) {
                        String sid = mnc;// 系统标识 mobileNetworkCode
                        int bid = gsm.getCid();// 基站小区号 cellId
                        int nid = gsm.getLac();// 网络标识 locationAreaCode
                        location = LocationHelper.getLocation(sid, bid, nid, mobileCountryCode, RadioType.GSM);
                    } else {
                        Log.e(tag, "no GsmCellLocation");
                    }
                } else if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
                    CdmaCellLocation cdma = (CdmaCellLocation) telephonyManager.getCellLocation();
                    if (cdma != null) {
                        if (cdma.getBaseStationLatitude() != Integer.MAX_VALUE) {
                            double lat = (double) cdma.getBaseStationLatitude() / 14400;
                            double lon = (double) cdma.getBaseStationLongitude() / 14400;
                            location = new Location(lat, lon);
                        } else {
                            String sid = String.valueOf(cdma.getSystemId());// 系统标识mobileNetworkCode
                            int bid = cdma.getBaseStationId();// 基站小区号 cellId
                            int nid = cdma.getNetworkId();// 网络标识
                                                          // locationAreaCode
                            location = LocationHelper.getLocation(sid, bid, nid, mobileCountryCode, RadioType.CDMA);
                        }
                    } else {
                        Log.e(tag, "can get cdma cell location");
                    }
                } else {
                    Log.e(tag, "no suitable PHONE_TYPE");
                }
                
            } catch (Exception e) {
                Looper.prepare();
                locationManager = (LocationManager) context.getSystemService(Activity.LOCATION_SERVICE);
                long start = System.currentTimeMillis();
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new NetWorkLocationListener());
                while (UploadLocationService.this.location == null && System.currentTimeMillis() - start < 5000) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        Log.e(tag, e1.getMessage(), e1);
                    }
                }
                if (UploadLocationService.this.location == null) {
                    android.location.Location loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (loc != null) {
                        UploadLocationService.this.location = new Location(loc.getLatitude(), loc.getLongitude());
                    }
                    
                }
            }
        }
        
    }
    
    class NetWorkLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(android.location.Location loc) {
            UploadLocationService.this.location = new Location(loc.getLatitude(), loc.getLongitude());
        }
        
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
            
        }
    }
    
}
